import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//N叉树的层序遍历
//https://leetcode.cn/problems/n-ary-tree-level-order-traversal/description/
public class Test {
    public static void main(String[] args) {
        //
        Solution s = new Solution();
        Node root = new Node();
        s.levelOrder(root);
    }
}



// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
    }
};

//方法一：自己写的（听完老师讲思路）
class Solution1 {
    public List<List<Integer>> levelOrder(Node root) {

        Queue<Node> queue = new LinkedList<Node>();
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root == null)
            return res;
        queue.add(root);
        int len = 0;//每行的元素个数
        while (!queue.isEmpty()) {
            len = queue.size();
            List<Integer> line = new ArrayList<>();//行遍历，存放每行的元素
            for (int i = 0; i < len; i++) {
                Node node = queue.poll();
                //if(node!=null)
                line.add(node.val);
                queue.addAll(node.children);
            }
            res.add(line);
        }
        return res;
    }
}

//方法二：老师写的
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        //
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) return ret;
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        while(!q.isEmpty()) {
            int sz = q.size();
            List<Integer> tmp = new ArrayList<>();
            for(int i = 0; i < sz; i++){
                Node t = q.poll();
                tmp.add(t.val);
                for(Node child : t.children){//这种写法
                    if(child != null)
                        q.add(child);
                }
            }
            ret.add(tmp);
        }
        return ret;
    }
}